import * as cc from 'cc';
import { FixedKeyInput } from '../../2d-platform/script/core/FixedKeyInput';
const { ccclass, property } = cc._decorator;

export type SamplerData = {
    up: boolean;
    right: boolean;
    down: boolean;
    left: boolean;
    fire: boolean;
};

function initSamplerData(): SamplerData {
    return {
        left: false,
        right: false,
        up: false,
        down: false,
        fire: false,
    };
}

export class InputSampler {
    sampler: SamplerData;
    constructor(private fixedKeyInput: FixedKeyInput) {
        this.sampler = initSamplerData();
    }

    tickSample() {
        const s = initSamplerData();
        if (this.fixedKeyInput.getKey(cc.KeyCode.ARROW_LEFT)) {
            s.left = true;
        }
        if (this.fixedKeyInput.getKey(cc.KeyCode.ARROW_RIGHT)) {
            s.right = true;
        }
        if (this.fixedKeyInput.getKey(cc.KeyCode.ARROW_UP)) {
            s.up = true;
        }
        if (this.fixedKeyInput.getKey(cc.KeyCode.ARROW_DOWN)) {
            s.down = true;
        }
        if (this.fixedKeyInput.getKeyDown(cc.KeyCode.SPACE)) {
            s.fire = true;
        }
        this.sampler = s;
        return s;
    }

    //将sample转化成mask
    sampleMask(): number {
        let sample = this.sampler;
        let m = 0;
        if (sample.left) m |= 1 << 0; // left -> bit 0
        if (sample.right) m |= 1 << 1; // right -> bit 1
        if (sample.up) m |= 1 << 2; // up -> bit 2
        if (sample.down) m |= 1 << 3; // down -> bit 3
        if (sample.fire) m |= 1 << 4; // attack/fire -> bit 4
        return m;
    }

    //将mask转化成sample
    virtualSample(mask: number): SamplerData {
        const s = initSamplerData();
        s.left = (mask & (1 << 0)) !== 0;
        s.right = (mask & (1 << 1)) !== 0;
        s.up = (mask & (1 << 2)) !== 0;
        s.down = (mask & (1 << 3)) !== 0;
        s.fire = (mask & (1 << 4)) !== 0;
        return s;
    }
}
